package com.luo.backend.controller;

import com.luo.backend.common.ApiResponse;
import com.luo.backend.dto.MerchantStatisticsResponse;
import com.luo.backend.entity.User;
import com.luo.backend.repository.UserRepository;
import com.luo.backend.service.MerchantStatisticsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;

/**
 * 商家统计接口
 */
@RestController
@RequestMapping("/api/v1/merchant/statistics")
public class MerchantStatisticsController {
    
    private static final Logger logger = LoggerFactory.getLogger(MerchantStatisticsController.class);
    
    @Autowired
    private MerchantStatisticsService statisticsService;
    
    @Autowired
    private UserRepository userRepository;
    
    /**
     * 获取当前登录用户
     */
    private User getCurrentUser(Authentication authentication) {
        Long userId = (Long) authentication.getPrincipal();
        return userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
    }
    
    /**
     * 获取统计概览
     * GET /api/v1/merchant/statistics/overview?date=2025-10-08
     */
    @GetMapping("/overview")
    public ApiResponse<MerchantStatisticsResponse> getStatisticsOverview(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            MerchantStatisticsResponse statistics = statisticsService.getStatisticsOverview(
                user.getMerchantId(), date);
            
            return ApiResponse.success(statistics);
            
        } catch (Exception e) {
            logger.error("获取统计概览失败", e);
            return ApiResponse.error("获取统计概览失败：" + e.getMessage());
        }
    }
}





